import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:tihai/entity/problem.dart';
import 'package:tihai/util/network.dart';

import '../../entity/result.dart';
import '../../util/storage.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  dynamic dataList;
  dynamic loginId;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  void deactivate() {
    super.deactivate();

  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: initData(),
    );
  }

  Widget initData() {
    return ListView.builder(
        itemCount: dataList == null ? 0 : dataList.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () {},
            child: Card(
              margin: const EdgeInsets.all(10.0),
              child: Column(
                children: dataList == null ? [] : [
                  Text(
                    "题目：${dataList[index].title}",
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis, // 显示不完，就在后面显示点点
                    style: const TextStyle(
                      fontSize: 18.0, // 文字大小
                      color: Colors.blueAccent, // 文字颜色
                    ),
                  ),
                  Text(
                    "奖励：${dataList[index].score}金币", maxLines: 3,
                    overflow: TextOverflow.ellipsis, // 显示不完，就在后面显示点点
                    style: const TextStyle(
                      fontSize: 18.0, // 文字大小
                      color: Colors.orangeAccent, // 文字颜色
                    ),
                  ),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "A");
                      },
                      child: Text("选项A：${dataList[index].choiceA}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "B");
                      },
                      child: Text("选项B：${dataList[index].choiceB}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "C");
                      },
                      child: Text("选项C：${dataList[index].choiceC}")),
                  ElevatedButton(
                      onPressed: () {
                        checkAnswer(index, "D");
                      },
                      child: Text("选项D：${dataList[index].choiceD}")),
                ],
              ),
            ),
          );
        });
  }

  void checkAnswer(int index, String choice) async {
    if (choice == dataList[index].answer) {
      Fluttertoast.showToast(
          msg: "回答正确,奖励${dataList[index].score}金币",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.blueAccent,
          textColor: Colors.white,
          fontSize: 16.0);
      Map<String, dynamic> data = {};
      data["problemId"] = "${dataList[index].id}";
      data["score"] = "${dataList[index].score}";
      data["askId"] = "$loginId";
      Result result = await postAPI(API.deleteProblemById, data);
    } else {
      Fluttertoast.showToast(
          msg: "回答错误,扣除${(dataList[index].score / 2).round()}金币",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.redAccent,
          textColor: Colors.white,
          fontSize: 16.0);
      Map<String, dynamic> data = {};
      data["problemId"] = "${dataList[index].id}";
      data["score"] = "${-(dataList[index].score / 2).round()}";
      data["askId"] = "$loginId";
      Result result = await postAPI(API.deleteProblemById, data);
    }
  }

  void loadData() async {
    var result = await getListAPI(ProblemBean(), API.selectProblemList, {});
    var answerId = await Storage.getString("userId");
    setState(() {
      dataList = result;
      loginId = answerId;
    });
  }
}
